package com.openbravo.pos.payment;

import com.openbravo.data.loader.LocalRes;
import com.openbravo.pos.forms.AppLocal;
import com.openbravo.pos.forms.AppProperties;
import com.openbravo.pos.util.AltEncrypter;
import com.openbravo.pos.util.StringUtils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Currency;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class PaymentGatewayCaixa
  implements PaymentGateway
{
  private static String ENDPOINTADDRESS;
  private static final String SALE = "A";
  private static final String REFUND = "3";
  private static String SALEAPPROVED = "0000";
  private static String REFUNDAPPROVED = "0900";
  private String m_sCurrency;
  private String sMerchantCode;
  private String sTerminal;
  private String sCommerceSign;
  private boolean bSha;
  private boolean m_bTestMode;

  public PaymentGatewayCaixa(AppProperties paramAppProperties)
  {
    AltEncrypter localAltEncrypter = new AltEncrypter("cypherkey");
    this.sCommerceSign = localAltEncrypter.decrypt(paramAppProperties.getProperty("payment.commercesign").substring(6));
    this.m_bTestMode = Boolean.valueOf(paramAppProperties.getProperty("payment.testmode")).booleanValue();
    this.m_sCurrency = (Locale.getDefault().getCountry().isEmpty() ? Currency.getInstance("EUR").getCurrencyCode() : Currency.getInstance(Locale.getDefault()).getCurrencyCode());
    this.sTerminal = paramAppProperties.getProperty("payment.terminal");
    this.sMerchantCode = paramAppProperties.getProperty("payment.commerceid");
    this.bSha = Boolean.valueOf(paramAppProperties.getProperty("payment.SHA")).booleanValue();
    ENDPOINTADDRESS = this.m_bTestMode ? "https://sis-t.sermepa.es:25443/sis/operaciones" : "https://sis.sermepa.es/sis/realizarPago";
  }

  public PaymentGatewayCaixa()
  {
  }

  private String createOrderId()
  {
    Random localRandom = new Random();
    DecimalFormat localDecimalFormat = new DecimalFormat("0000000000");
    return localDecimalFormat.format(Math.abs(localRandom.nextInt()) + Math.abs(System.currentTimeMillis()) % 1000000L);
  }

  public void execute(PaymentInfoMagcard paramPaymentInfoMagcard)
  {
    StringBuffer localStringBuffer = new StringBuffer();
    String str1 = "978";
    String str2 = "";
    if (this.m_sCurrency.equals("USD"))
      str1 = "840";
    else if (this.m_sCurrency.equals("GPD"))
      str1 = "826";
    DecimalFormat localDecimalFormat = new DecimalFormat("00");
    String str3 = localDecimalFormat.format(Math.abs(paramPaymentInfoMagcard.getTotal()) * 100.0D);
    String str4 = createOrderId();
    try
    {
    	Object localObject;
	if (paramPaymentInfoMagcard.getTotal() > 0.0D)
      {
        localObject = str3 + str4 + this.sMerchantCode + str1 + paramPaymentInfoMagcard.getCardNumber() + "A" + this.sCommerceSign;
        str2 = "<DATOSENTRADA><DS_Version>0.1</DS_Version><DS_MERCHANT_AMOUNT>" + str3 + "</DS_MERCHANT_AMOUNT>" + "<DS_MERCHANT_CURRENCY>" + str1 + "</DS_MERCHANT_CURRENCY>" + "<DS_MERCHANT_ORDER>" + str4 + "</DS_MERCHANT_ORDER>" + "<DS_MERCHANT_MERCHANTCODE>" + this.sMerchantCode + "</DS_MERCHANT_MERCHANTCODE>" + "<DS_MERCHANT_MERCHANTURL></DS_MERCHANT_MERCHANTURL>" + "<DS_MERCHANT_MERCHANTSIGNATURE>" + getSHA1((String)localObject) + "</DS_MERCHANT_MERCHANTSIGNATURE>" + "<DS_MERCHANT_TERMINAL>" + this.sTerminal + "</DS_MERCHANT_TERMINAL>" + "<DS_MERCHANT_TRANSACTIONTYPE>" + "A" + "</DS_MERCHANT_TRANSACTIONTYPE>" + "<DS_MERCHANT_PAN>" + paramPaymentInfoMagcard.getCardNumber() + "</DS_MERCHANT_PAN>" + "<DS_MERCHANT_EXPIRYDATE>" + paramPaymentInfoMagcard.getExpirationDate() + "</DS_MERCHANT_EXPIRYDATE>" + "</DATOSENTRADA>";
      }
      else
      {
        localObject = str3 + paramPaymentInfoMagcard.getTransactionID() + this.sMerchantCode + str1 + "3" + this.sCommerceSign;
        str2 = "<DATOSENTRADA><DS_Version>0.1</DS_Version><DS_MERCHANT_AMOUNT>" + str3 + "</DS_MERCHANT_AMOUNT>" + "<DS_MERCHANT_CURRENCY>" + str1 + "</DS_MERCHANT_CURRENCY>" + "<DS_MERCHANT_ORDER>" + paramPaymentInfoMagcard.getTransactionID() + "</DS_MERCHANT_ORDER>" + "<DS_MERCHANT_MERCHANTCODE>" + this.sMerchantCode + "</DS_MERCHANT_MERCHANTCODE>" + "<DS_MERCHANT_MERCHANTURL></DS_MERCHANT_MERCHANTURL>" + "<DS_MERCHANT_MERCHANTSIGNATURE>" + getSHA1((String)localObject) + "</DS_MERCHANT_MERCHANTSIGNATURE>" + "<DS_MERCHANT_TERMINAL>" + this.sTerminal + "</DS_MERCHANT_TERMINAL>" + "<DS_MERCHANT_TRANSACTIONTYPE>" + "3" + "</DS_MERCHANT_TRANSACTIONTYPE>" + "</DATOSENTRADA>";
      }
      localStringBuffer.append("entrada=" + URLEncoder.encode(str2, "UTF-8"));
        localObject = new URL(ENDPOINTADDRESS);
      URLConnection localURLConnection = ((URL)localObject).openConnection();
      localURLConnection.setDoOutput(true);
      localURLConnection.setUseCaches(false);
      localURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      DataOutputStream localDataOutputStream = new DataOutputStream(localURLConnection.getOutputStream());
      localDataOutputStream.write(localStringBuffer.toString().getBytes());
      localDataOutputStream.flush();
      localDataOutputStream.close();
      BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(localURLConnection.getInputStream()));
      String str5 = localBufferedReader.readLine();
      localBufferedReader.close();
      if (str5 == null)
      {
        paramPaymentInfoMagcard.paymentError(AppLocal.getIntString("message.paymenterror"), "Response empty.");
      }
      else
      {
        LaCaixaParser localLaCaixaParser = new LaCaixaParser(str5);
        Map localMap = localLaCaixaParser.splitXML();
        if (localLaCaixaParser.getResult().equals(LocalRes.getIntString("button.ok")))
        {
          if ((SALEAPPROVED.equals(localMap.get("Ds_Response"))) || (REFUNDAPPROVED.equals(localMap.get("Ds_Response"))))
          {
            paramPaymentInfoMagcard.paymentOK((String)localMap.get("Ds_AuthorisationCode"), (String)localMap.get("Ds_Order"), str5);
          }
          else
          {
            String str6 = (String)localMap.get("Ds_Response");
            if ("0101".equals(str6))
              paramPaymentInfoMagcard.paymentError(AppLocal.getIntString("message.paymentnotauthorised"), "Card date expired");
            else if ("0102".equals(str6))
              paramPaymentInfoMagcard.paymentError(AppLocal.getIntString("message.paymenterror"), "Tarjeta en excepción transitoria o bajo sospecha de fraude.");
            else if ("0104".equals(str6))
              paramPaymentInfoMagcard.paymentError(AppLocal.getIntString("message.paymenterror"), "Operación no permitida para esa tarjeta o terminal.");
            else if ("0116".equals(str6))
              paramPaymentInfoMagcard.paymentError(AppLocal.getIntString("message.paymenterror"), "Disponible insuficiente.");
            else if ("0118".equals(str6))
              paramPaymentInfoMagcard.paymentError(AppLocal.getIntString("message.paymenterror"), "Tarjeta no registrada.");
            else if ("0129".equals(str6))
              paramPaymentInfoMagcard.paymentError(AppLocal.getIntString("message.paymenterror"), "CVV2 security code invalid. Amount not supplied or invalid.");
            else if ("0180".equals(str6))
              paramPaymentInfoMagcard.paymentError(AppLocal.getIntString("message.paymenterror"), "Tarjeta ajena al servicio.");
            else if ("0184".equals(str6))
              paramPaymentInfoMagcard.paymentError(AppLocal.getIntString("message.paymenterror"), "Cardholder authentication error.");
            else if ("0190".equals(str6))
              paramPaymentInfoMagcard.paymentError(AppLocal.getIntString("message.paymenterror"), "Denegation of service without reason.");
            else if ("0191".equals(str6))
              paramPaymentInfoMagcard.paymentError(AppLocal.getIntString("message.paymenterror"), "Expiry date invalid.");
            else if ("0202".equals(str6))
              paramPaymentInfoMagcard.paymentError(AppLocal.getIntString("message.paymenterror"), "Tarjeta en excepción transitoria o bajo sospecha de fraude con retirada de tarjeta.");
            else if ("0904".equals(str6))
              paramPaymentInfoMagcard.paymentError(AppLocal.getIntString("message.paymenterror"), "Comercio no registrado en FUC.");
            else if (("9912".equals(str6)) || ("912".equals(str6)))
              paramPaymentInfoMagcard.paymentError(AppLocal.getIntString("message.paymenterror"), "Emisor no disponible.");
            else
              paramPaymentInfoMagcard.paymentError(AppLocal.getIntString("message.paymenterrorunknown"), "");
            str6 = (String)localMap.get("CODIGO");
            if ("SIS0054".equals(str6))
              paramPaymentInfoMagcard.paymentError(AppLocal.getIntString("message.paymentnotauthorised"), "Pedido repetido.");
            else if ("SIS0078".equals(str6))
              paramPaymentInfoMagcard.paymentError(AppLocal.getIntString("message.paymenterror"), "Método de pago no disponible para su tarjeta.");
            else if ("SIS0093".equals(str6))
              paramPaymentInfoMagcard.paymentError(AppLocal.getIntString("message.paymenterror"), "Tarjeta no válida.");
            else if ("SIS0094".equals(str6))
              paramPaymentInfoMagcard.paymentError(AppLocal.getIntString("message.paymenterror"), "Error en la llamada al MPI sin controlar.");
          }
        }
        else
          paramPaymentInfoMagcard.paymentError(localLaCaixaParser.getResult(), "");
      }
    }
    catch (UnsupportedEncodingException localUnsupportedEncodingException)
    {
      paramPaymentInfoMagcard.paymentError(AppLocal.getIntString("message.paymentexceptionservice"), localUnsupportedEncodingException.getMessage());
    }
    catch (MalformedURLException localMalformedURLException)
    {
      paramPaymentInfoMagcard.paymentError(AppLocal.getIntString("message.paymentexceptionservice"), localMalformedURLException.getMessage());
    }
    catch (IOException localIOException)
    {
      paramPaymentInfoMagcard.paymentError(AppLocal.getIntString("message.paymenterror"), localIOException.getMessage());
    }
  }

  public String getSHA1(String paramString)
  {
    byte[] arrayOfByte = null;
    try
    {
      MessageDigest localMessageDigest = MessageDigest.getInstance("SHA1");
      localMessageDigest.update(paramString.getBytes());
      arrayOfByte = localMessageDigest.digest();
    }
    catch (Exception localException)
    {
      System.out.println("Exception: " + localException);
    }
    return StringUtils.byte2hex(arrayOfByte);
  }

  public class LaCaixaParser extends DefaultHandler
  {
    private SAXParser m_sp = null;
    private Map props = new HashMap();
    private String text;
    private InputStream is;
    private String result;

    public LaCaixaParser(String arg2)
    {
      Object localObject;
      this.is = new ByteArrayInputStream(arg2.getBytes());
    }

    public Map splitXML()
    {
      try
      {
        if (this.m_sp == null)
        {
          SAXParserFactory localSAXParserFactory = SAXParserFactory.newInstance();
          this.m_sp = localSAXParserFactory.newSAXParser();
        }
        this.m_sp.parse(this.is, this);
      }
      catch (ParserConfigurationException localParserConfigurationException)
      {
        this.result = LocalRes.getIntString("exception.parserconfig");
      }
      catch (SAXException localSAXException)
      {
        this.result = LocalRes.getIntString("exception.xmlfile");
      }
      catch (IOException localIOException)
      {
        this.result = LocalRes.getIntString("exception.iofile");
      }
      this.result = LocalRes.getIntString("button.ok");
      return this.props;
    }

    public void endElement(String paramString1, String paramString2, String paramString3)
      throws SAXException
    {
      try
      {
        if (paramString3.equals("CODIGO"))
        {
          this.props.put("CODIGO", URLDecoder.decode(this.text, "UTF-8"));
          this.text = "";
        }
        else if (paramString3.equals("Ds_Version"))
        {
          this.props.put("Ds_Version", URLDecoder.decode(this.text, "UTF-8"));
          this.text = "";
        }
        else if (paramString3.equals("Ds_Amount"))
        {
          this.props.put("Ds_Amount", URLDecoder.decode(this.text, "UTF-8"));
          this.text = "";
        }
        else if (paramString3.equals("Ds_Currency"))
        {
          this.props.put("Ds_Currency", URLDecoder.decode(this.text, "UTF-8"));
          this.text = "";
        }
        else if (paramString3.equals("Ds_Order"))
        {
          this.props.put("Ds_Order", URLDecoder.decode(this.text, "UTF-8"));
          this.text = "";
        }
        else if (paramString3.equals("Ds_Signature"))
        {
          this.props.put("Ds_Signature", URLDecoder.decode(this.text, "UTF-8"));
          this.text = "";
        }
        else if (paramString3.equals("Ds_Terminal"))
        {
          this.props.put("Ds_Terminal", URLDecoder.decode(this.text, "UTF-8"));
          this.text = "";
        }
        else if (paramString3.equals("Ds_Response"))
        {
          this.props.put("Ds_Response", URLDecoder.decode(this.text, "UTF-8"));
          this.text = "";
        }
        else if (paramString3.equals("Ds_AuthorisationCode"))
        {
          this.props.put("Ds_AuthorisationCode", URLDecoder.decode(this.text, "UTF-8"));
          this.text = "";
        }
        else if (paramString3.equals("Ds_TransactionType"))
        {
          this.props.put("Ds_TransactionType", URLDecoder.decode(this.text, "UTF-8"));
          this.text = "";
        }
        else if (paramString3.equals("Ds_SecurePayment"))
        {
          this.props.put("Ds_SecurePayment", URLDecoder.decode(this.text, "UTF-8"));
          this.text = "";
        }
        else if (paramString3.equals("Ds_Language"))
        {
          this.props.put("Ds_Language", URLDecoder.decode(this.text, "UTF-8"));
          this.text = "";
        }
        else if (paramString3.equals("Ds_MerchantData"))
        {
          this.props.put("Ds_MerchantData", URLDecoder.decode(this.text, "UTF-8"));
          this.text = "";
        }
        else if (paramString3.equals("Ds_Card_Country"))
        {
          this.props.put("Ds_Card_Country", URLDecoder.decode(this.text, "UTF-8"));
          this.text = "";
        }
      }
      catch (UnsupportedEncodingException localUnsupportedEncodingException)
      {
        this.result = localUnsupportedEncodingException.getMessage();
      }
    }

    public void startDocument()
      throws SAXException
    {
      this.text = new String();
    }

    public void endDocument()
      throws SAXException
    {
    }

    public void characters(char[] paramArrayOfChar, int paramInt1, int paramInt2)
      throws SAXException
    {
      if (this.text != null)
        this.text = new String(paramArrayOfChar, paramInt1, paramInt2);
    }

    public String getResult()
    {
      return this.result;
    }
  }
}

/* Location:           D:\PowerFulPOS-2.30.2\openbravopos.jar
 * Qualified Name:     com.openbravo.pos.payment.PaymentGatewayCaixa
 * JD-Core Version:    0.6.0
 */